package com.duojuhe.common.utils.servletutils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 客户端工具类
 * 
 */
public class ServletUtils {
    /**
     * 获取String参数
     */
    public static String getParameter(String name){
        return getRequest().getParameter(name);
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse(){
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession(){
        return getRequest().getSession();
    }

    /**
     * 获取 ServletRequestAttributes
     * @return
     */
    private static ServletRequestAttributes getRequestAttributes(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }


    /**
     * 获得参数值
     * @param request
     * @return
     */
    public static String getParameterValueByRequest(String parameterName,HttpServletRequest request){
        //获取参数值
        if (StringUtils.isBlank(request.getParameter(parameterName))){
            return request.getParameter(parameterName);
        }else{
            return request.getHeader(parameterName);
        }
    }

}
